package com.example.shiro.controller;

import com.example.shiro.entity.User;
import com.example.shiro.service.UserService;
import com.example.shiro.util.ApiResult;
import com.example.shiro.util.ResultCodeEnum;
import com.example.shiro.util.ResultGenerator;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * @author lijilong
 * @version 1.0
 * @Description:
 * @CreateDate 2018/8/8 14:20
 */
@Slf4j
@Controller
public class LoginController {
    @Autowired
    UserService userService;

    @GetMapping("/login")
    public String login(){
        return "login";
    }

    @PostMapping("/loginUser")
    public String loginUser(String username, String password, boolean rememberMe, HttpSession session){
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        Subject subject = SecurityUtils.getSubject();
        try {
            token.setRememberMe(rememberMe);
            subject.login(token);   //完成登录
            User user = (User) subject.getPrincipal();
            session.setAttribute("user", user);
            if(subject.hasRole("admin")){
                log.info(username + "有admin角色");
            }else {
                log.info(username + "没有admin角色");
            }
            if(subject.isPermitted("delete")){
                log.info(username + "有delete权限");
            }else {
                log.info(username + "没有delete权限");
            }
            return "index";
        } catch(Exception e) {
            log.info("{用户名或密码有误}", e);
            return "login";//返回登录页面
        }
    }

    @GetMapping("/403")
    public String error(){
        return "403";
    }

    @GetMapping("/loginOut")
    public String loginOut(){
        log.info("登出");
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:login";
    }

    @RequiresRoles(value = "admin")
    @GetMapping("/delete")
    @ResponseBody
    public ApiResult delete(){
        return ResultGenerator.getSuccessResult("有admin角色");
    }

    @RequiresPermissions(value = "add")
    @GetMapping("/add")
    @ResponseBody
    public ApiResult add(){
        return ResultGenerator.getSuccessResult("有add权限");
    }

    @RequiresPermissions(value = "query")
    @GetMapping("/query")
    @ResponseBody
    public ApiResult query(){
        return ResultGenerator.getSuccessResult("有query权限");
    }

}
